package com.chhuang.mongo.core.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 
 * @author 黄晨
 *
 */
public class LoginFilter implements Filter {
	
	protected boolean autoLogin = false;
	protected boolean needForward = false;
	private static String skips[] = null;
	private static String sessionKey = null;
	private static String loginPage = null;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest)request;
		HttpServletResponse hresponse=(HttpServletResponse)response;
		
		if(autoLogin){
			chain.doFilter(request,response);
			return;
		}
		if (skips != null && this.needSkipUserLoginCheck(hrequest)){
			chain.doFilter(request,response);
			return;
		}
		
		if(hrequest.getSession(false)==null || hrequest.getSession(false).getAttribute(sessionKey)==null) {
			if(needForward){
				hrequest.getRequestDispatcher(loginPage).forward(hrequest, hresponse);
			}else{
				hresponse.sendRedirect(hrequest.getContextPath()+loginPage);
			}
		} else {
			chain.doFilter(hrequest, hresponse);
		}
	}
	
	private boolean needSkipUserLoginCheck(HttpServletRequest r) {
		boolean result = false;
		String uri = r.getRequestURI();

		//过滤掉直接输入根路径 或者 根路径 + / 这些
        if (uri.equals(r.getContextPath()) || uri.equals(r.getContextPath()+"/")){
        	return true;
        }

		for (String s : skips ) {
			if( uri.indexOf(s) > -1 ){
				result = true;
				break;
			}
		}

		return result;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String value = config.getInitParameter("autoLogin");
		if (value != null && (value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("true"))) {
			autoLogin = true;
		}
		String forward = config.getInitParameter("needForward");
		if (forward != null && (forward.equalsIgnoreCase("yes") || forward.equalsIgnoreCase("true"))) {
			needForward = true;
		}
		String skip = config.getInitParameter("skip");
		if (skip != null) {
			skips = skip.split(";");
		}
		loginPage = config.getInitParameter("loginPage");
		loginPage = loginPage.startsWith("/")?loginPage:"/"+loginPage;
		sessionKey = config.getInitParameter("sessionKey");
	}
	
	@Override
	public void destroy() {
		autoLogin = false;
		skips = null;
	}


}
